import { NativeModules, Platform } from 'react-native';
import { PLATFORM_CONFIGS } from '../utils/constants';

class PlatformAdapter {
  constructor() {
    this.installedPlatforms = [];
    this.currentPlatform = null;
  }

  /**
   * 获取平台配置
   */
  static getConfig(platform) {
    return PLATFORM_CONFIGS[platform] || PLATFORM_CONFIGS.douyin;
  }

  /**
   * 获取所有支持的平台
   */
  static getSupportedPlatforms() {
    return Object.keys(PLATFORM_CONFIGS).map(key => ({
      key,
      name: PLATFORM_CONFIGS[key].name,
      packageName: PLATFORM_CONFIGS[key].packageName
    }));
  }

  /**
   * 检测已安装的平台应用
   */
  static async detectInstalledPlatforms() {
    try {
      const supportedPlatforms = this.getSupportedPlatforms();
      const installedPlatforms = [];

      // 本地视频始终可用
      installedPlatforms.push({
        key: 'local',
        name: PLATFORM_CONFIGS.local.name,
        installed: true
      });

      // 检测其他应用是否安装
      for (const platform of supportedPlatforms) {
        if (platform.key === 'local') continue;
        
        if (platform.packageName) {
          const isInstalled = await this.isAppInstalled(platform.packageName);
          if (isInstalled) {
            installedPlatforms.push({
              key: platform.key,
              name: platform.name,
              packageName: platform.packageName,
              installed: true
            });
          }
        }
      }

      console.log('检测到已安装平台:', installedPlatforms);
      return installedPlatforms;
    } catch (error) {
      console.error('检测已安装平台失败:', error);
      // 返回基础配置（至少包含本地视频）
      return [{
        key: 'local',
        name: PLATFORM_CONFIGS.local.name,
        installed: true
      }];
    }
  }

  /**
   * 检查应用是否安装
   */
  static async isAppInstalled(packageName) {
    if (!packageName) return false;

    try {
      if (NativeModules.AppChecker) {
        return await NativeModules.AppChecker.isAppInstalled(packageName);
      } else {
        // 如果没有原生模块，返回true（假设已安装）
        console.warn('AppChecker原生模块未找到，假设应用已安装');
        return true;
      }
    } catch (error) {
      console.error(`检查应用安装状态失败: ${packageName}`, error);
      return false;
    }
  }

  /**
   * 启动应用
   */
  static async launchApp(platform) {
    const config = this.getConfig(platform);
    
    if (!config.packageName) {
      console.log('本地视频模式，无需启动应用');
      return true;
    }

    try {
      if (NativeModules.AppLauncher) {
        return await NativeModules.AppLauncher.launchApp(config.packageName);
      } else {
        console.warn('AppLauncher原生模块未找到');
        return false;
      }
    } catch (error) {
      console.error(`启动应用失败: ${config.packageName}`, error);
      throw error;
    }
  }

  /**
   * 获取平台特定的滑动配置
   */
  static getSwipeConfig(platform, screenWidth, screenHeight) {
    const config = this.getConfig(platform);
    
    return {
      startX: Math.round(screenWidth * config.startXRatio),
      startY: Math.round(screenHeight * config.startYRatio),
      endX: Math.round(screenWidth * config.endXRatio),
      endY: Math.round(screenHeight * config.endYRatio),
      duration: this.getSwipeDuration(config.swipeType),
      adAvoidRegions: config.adAvoidRegions.map(region => ({
        x: Math.round(screenWidth * region.x),
        y: Math.round(screenHeight * region.y),
        width: Math.round(screenWidth * region.width),
        height: Math.round(screenHeight * region.height)
      }))
    };
  }

  /**
   * 获取滑动持续时间
   */
  static getSwipeDuration(swipeType = 'vertical') {
    const baseDuration = 500; // 基础500ms
    
    switch (swipeType) {
      case 'horizontal':
        return baseDuration * 0.8; // 水平滑动稍快
      case 'vertical':
      default:
        return baseDuration;
    }
  }

  /**
   * 检查当前前台应用
   */
  static async getCurrentApp() {
    try {
      if (NativeModules.AppChecker) {
        return await NativeModules.AppChecker.getCurrentApp();
      } else {
        console.warn('AppChecker原生模块未找到');
        return null;
      }
    } catch (error) {
      console.error('获取当前应用失败:', error);
      return null;
    }
  }

  /**
   * 验证平台是否匹配当前应用
   */
  static async validateCurrentPlatform(platform) {
    const config = this.getConfig(platform);
    
    if (!config.packageName) {
      // 本地视频模式，始终返回true
      return true;
    }

    try {
      const currentApp = await this.getCurrentApp();
      
      if (!currentApp) {
        console.warn('无法获取当前应用信息');
        return true; // 无法验证时默认通过
      }

      const isValid = currentApp === config.packageName;
      
      if (!isValid) {
        console.warn(`平台不匹配: 期望 ${config.packageName}, 实际 ${currentApp}`);
      }
      
      return isValid;
    } catch (error) {
      console.error('验证平台失败:', error);
      return true; // 验证失败时默认通过
    }
  }

  /**
   * 获取平台图标（如果有的话）
   */
  static async getPlatformIcon(platform) {
    const config = this.getConfig(platform);
    
    if (!config.packageName) {
      return null; // 本地视频没有图标
    }

    try {
      if (NativeModules.AppChecker) {
        return await NativeModules.AppChecker.getAppIcon(config.packageName);
      }
    } catch (error) {
      console.error(`获取平台图标失败: ${platform}`, error);
    }
    
    return null;
  }

  /**
   * 获取平台版本信息
   */
  static async getPlatformVersion(platform) {
    const config = this.getConfig(platform);
    
    if (!config.packageName) {
      return null;
    }

    try {
      if (NativeModules.AppChecker) {
        return await NativeModules.AppChecker.getAppVersion(config.packageName);
      }
    } catch (error) {
      console.error(`获取平台版本失败: ${platform}`, error);
    }
    
    return null;
  }

  /**
   * 获取平台详细信息
   */
  static async getPlatformDetails(platform) {
    const config = this.getConfig(platform);
    const [icon, version, isInstalled] = await Promise.all([
      this.getPlatformIcon(platform),
      this.getPlatformVersion(platform),
      this.isAppInstalled(config.packageName)
    ]);

    return {
      key: platform,
      name: config.name,
      packageName: config.packageName,
      swipeType: config.swipeType,
      icon,
      version,
      isInstalled,
      config: {
        startXRatio: config.startXRatio,
        startYRatio: config.startYRatio,
        endXRatio: config.endXRatio,
        endYRatio: config.endYRatio,
        adAvoidRegions: config.adAvoidRegions
      }
    };
  }

  /**
   * 获取所有平台的详细信息
   */
  static async getAllPlatformDetails() {
    const platforms = this.getSupportedPlatforms();
    const details = [];

    for (const platform of platforms) {
      try {
        const detail = await this.getPlatformDetails(platform.key);
        details.push(detail);
      } catch (error) {
        console.error(`获取平台详情失败: ${platform.key}`, error);
        // 即使失败也添加基础信息
        details.push({
          key: platform.key,
          name: platform.name,
          packageName: platform.packageName,
          error: error.message
        });
      }
    }

    return details;
  }
}

export default PlatformAdapter;